<template>
    <div class="calendar-container">
      <!-- 导航：左右切换月份 -->
      <div class="navigation">
        <button class="nav-button" @click="prevMonth">&lsaquo;</button>
        <span class="current-month">{{ currentYear }}年{{ currentMonth + 1 }}月</span>
        <button class="nav-button" @click="nextMonth">&rsaquo;</button>
      </div>
  
      <!-- 当月日历 -->
      <div class="month-calendar card">
        <!-- 星期标题 -->
        <div class="weekdays">
          <div>日</div>
          <div>一</div>
          <div>二</div>
          <div>三</div>
          <div>四</div>
          <div>五</div>
          <div>六</div>
        </div>
        <!-- 日历格子 -->
        <div class="calendar-days">
          <div
            v-for="(cell, i) in calendarCells"
            :key="i"
            :class="['cell', { blank: cell.isBlank, 'day-cell': !cell.isBlank }]"
            @click="!cell.isBlank && selectDate(currentYear, currentMonth, cell.day)"
          >
            <div class="day-number" v-if="!cell.isBlank">{{ cell.day }}</div>
            <!-- 如果该日期有金额数据，则展示 -->
            <div class="amount-show" v-if="!cell.isBlank && cell.price">
              {{ cell.price }}元
              
            </div>
            <div class="delete-price" @click.stop="deletePrice(cell.date)" v-if="cell.price > 0">×</div>
          </div>
        </div>
      </div>
  
      <!-- 金额输入弹框 -->
      <div v-if="showAmountModal" class="modal" @click.self="closeAmount">
        <div class="modal-content card">
          <span class="close" @click="closeAmount">&times;</span>
          <p class="modal-title">设置 {{ editingDate }} 的金额</p>
          <input
            type="number"
            v-model="amountInput"
            placeholder="请输入金额"
            class="modal-input"
          />
          <div class="modal-button-box">
            <button @click="setAmount" class="modal-button">保存</button>
            <button @click="showAmountModal = false" class="modal-button">取消</button>
        </div>
        </div>
        
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import { price_list, apiSetAmount, apiDeletePrice } from '@/api/room'
  import { useRoute } from 'vue-router'
  import feedback from '@/utils/feedback'

  // 当前显示的年份和月份（月份从 0 开始）
  const currentYear = ref(new Date().getFullYear())
  const currentMonth = ref(new Date().getMonth())
  
  // 存储日期对应的金额数据，key 格式：YYYY-MM-DD
  const amounts = ref({})
  
  // 当前正在编辑的日期（"YYYY-MM-DD"）
  const editingDate = ref('')
  // 弹框中输入的金额
  const amountInput = ref('')
  // 是否显示金额输入弹框
  const showAmountModal = ref(false)
  
  const route = useRoute()
  const roomId = route.query.id // 获取传递的 room_id
  
  /**
   * 格式化日期函数，输出 "YYYY-MM-DD" 格式的字符串
   */
  function formatDate(year, month, day) {
    const m = month + 1 < 10 ? '0' + (month + 1) : month + 1
    const d = day < 10 ? '0' + day : day
    return `${year}-${m}-${d}`
  }
  
  /**
   * 根据当前年份、月份计算日历格子
   * 数组中包含：前置空白格（用于对齐星期） + 实际日期格子
   */
  function getCalendarCells(year, month) {
    const cells = []
    const firstDay = new Date(year, month, 1).getDay() // 当月 1 号是星期几（0=星期日）
    const daysInMonth = new Date(year, month + 1, 0).getDate() // 当月天数
  
    // 补全前置空白单元格
    for (let i = 0; i < firstDay; i++) {
      cells.push({ isBlank: true })
    }
  
    // 填充当月日期
    for (let d = 1; d <= daysInMonth; d++) {
      cells.push({ isBlank: false, day: d })
    }
    return cells
  }
  
  // 计算属性，根据当前年月动态计算日历格子
  const calendarCells = computed(() => {
    const cells = []
    const firstDay = new Date(currentYear.value, currentMonth.value, 1).getDay() // 当月 1 号是星期几（0=星期日）
    const daysInMonth = new Date(currentYear.value, currentMonth.value + 1, 0).getDate() // 当月天数

    // 补全前置空白单元格
    for (let i = 0; i < firstDay; i++) {
        cells.push({ isBlank: true })
    }

    // 填充当月日期
    for (let d = 1; d <= daysInMonth; d++) {
        const date = formatDate(currentYear.value, currentMonth.value, d)
        const price = amounts.value[date] || 0 // 从后端数据中获取价格
        cells.push({ isBlank: false, day: d, date: date, price: price }) // 添加日期和价格属性
    }
    return cells
  })
  
  /**
   * 切换到上一个月，如果当前月份为 0 则切换到上一年的 12 月
   */
  function prevMonth() {
    let date = new Date()
    if(date.getFullYear() == currentYear.value && date.getMonth() == currentMonth.value){
        return false
    }
    currentMonth.value--
    if (currentMonth.value < 0) {
      currentMonth.value = 11
      currentYear.value--
    }

    getMonthlyData()
  }
  
  /**
   * 切换到下一个月，如果当前月份为 11 则切换到下一年的 1 月
   */
  function nextMonth() {
    currentMonth.value++
    if (currentMonth.value > 11) {
      currentMonth.value = 0
      currentYear.value++
    }

    getMonthlyData()
  }
  
  /**
   * 点击某一天时：
   * 1. 记录选中的日期（格式化后）
   * 2. 将已有金额（如果有）回显到输入框
   * 3. 打开金额输入弹框
   */
  function selectDate(year, month, day) {
    editingDate.value = formatDate(year, month, day)
    amountInput.value = amounts.value[editingDate.value] || ''
    showAmountModal.value = true
  }
  
  /** 关闭金额弹框 */
  function closeAmount() {
    showAmountModal.value = false
  }
  
  /** 保存金额：若输入为空则删除对应记录，否则更新金额 */
  function saveAmount() {
    if (!amountInput.value) {
      delete amounts.value[editingDate.value]
    } else {
      amounts.value[editingDate.value] = amountInput.value
    }
    showAmountModal.value = false
  }
  
  // 设置金额的函数
  const setAmount = async () => {
    try {
        // 假设有一个 API 用于设置金额
        const response = await apiSetAmount({ date: editingDate.value, price: amountInput.value, room_id: roomId });
        // if (response.code === 1) {
            // 更新本地数据
            amounts.value[editingDate.value] = amountInput.value.toFixed(2);
            showAmountModal.value = false
        // } else {
        //     console.error('设置金额失败:', response.msg);
        // }
    } catch (error) {
        console.error('设置金额时发生错误:', error);
    }
  };
  
  // 获取当月所有数据的函数
  const getMonthlyData = async () => {
    const formattedDate = `${currentYear.value}-${String(currentMonth.value + 1).padStart(2, '0')}`; // 格式化为 YYYY-MM
    const res = await price_list({
        date: formattedDate,
        room_id: roomId // 使用传递的 room_id
    });

    // 处理接口返回的数据
    // if (res.code == 1 && res.data) {
        // 清空现有的 amounts
        amounts.value = {};
        // 将接口返回的数据存储到 amounts 中
        res.forEach(item => {
            amounts.value[item.date] = item.price; // 将日期作为 key，价格作为 value
        });
    // } else {
    //     console.error('获取房间价格数据失败:', res.msg);
    // }
  };
  
  /** 删除价格 */
  const deletePrice = async (date) => {
    await feedback.confirm('确定删除该价格吗？')
      try {
        await apiDeletePrice({ date: date, room_id: roomId });
        amounts.value[date] = '';
        showAmountModal.value = false;
        getMonthlyData();
    } catch (error) {
      console.error('删除金额时发生错误:', error);
    }
  };
  
  onMounted(() => {
    getMonthlyData(); // 获取当月所有数据
  })
  </script>
  
  <style scoped>
  /* 全局字体和背景 */
  .calendar-container {
    max-width: 100%;
    margin: 0 auto;
    padding: 20px;
    text-align: center;
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    background: #f5f8fa;
    min-height: 82vh; /* 确保容器高度自适应 */
    display: flex;
    flex-direction: column;
  }
  
  /* 卡片效果 */
  .card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    width: 100%; /* 设置宽度为100% */
  }
  
  /* 导航部分 */
  .navigation {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .nav-button {
    background: linear-gradient(145deg, #4a90e2, #357ab8);
    border: none;
    color: #fff;
    padding: 10px;
    font-size: 24px;
    cursor: pointer;
    border-radius: 50%;
    transition: transform 0.2s;
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .nav-button:hover {
    transform: scale(1.05);
  }
  
  .current-month {
    font-size: 24px;
    font-weight: 600;
    margin: 0 20px;
    color: #333;
  }
  
  /* 日历面板 */
  .month-calendar {
    padding: 15px;
    margin-bottom: 15px;
    width: 100%; /* 设置宽度为100% */
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  /* 星期标题及日历格子 */
  .weekdays,
  .calendar-days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    margin-bottom: 10px;
  }
  
  .weekdays div {
    font-weight: 600;
    padding: 8px 0;
    font-size: 18px;
    color: #555;
  }
  
  .calendar-days {
    gap: 10px;
    flex: 1;
    width: 100%;
    height: 100%;
  }
  
  /* 日历单元格 */
  .cell {
    border: 1px solid #e6e6e6;
    min-height: 60px;
    position: relative;
    padding: 4px;
    font-size: 18px;
    border-radius: 6px;
    background: #fafafa;
    transition: background 0.2s;
    height: auto; /* 允许高度自适应 */
  }
  
  .cell:hover:not(.blank) {
    background: #eaf4ff;
  }
  
  .blank {
    background: transparent;
    cursor: default;
  }
  
  .day-cell {
    cursor: pointer;
  }
  
  .day-number {
    font-weight: 600;
    color: #333;
  }
  
  /* 金额显示 */
  .amount-show {
    position: absolute;
    bottom: 4px;
    left: 4px;
    right: 4px;
    background: rgba(52, 152, 219, 0.15);
    color: #2980b9;
    font-size: 14px;
    border-radius: 3px;
    padding: 2px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .delete-price {
    cursor: pointer;
    color: #ff0000;
    font-size: 24px;
    padding: 0 4px;
    position: absolute;
    right: 4px;
    top: 0px;
  }
  
  .delete-price:hover {
    opacity: 0.8;
  }
  
  /* 弹框样式 */
  .modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }
  
  .modal-content {
    padding: 20px;
    width: 90%;
    max-width: 400px;
  }
  
  .close {
    position: absolute;
    right: 15px;
    top: 10px;
    font-size: 28px;
    cursor: pointer;
  }
  
  /* 弹框内部 */
  .modal-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 15px;
    color: #333;
  }
  
  .modal-input {
    width: 100%;
    padding: 8px;
    margin-bottom: 15px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 6px;
  }
  
  .modal-button-box {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
  }
  
  .modal-button-box button {
    width: 48%;
    padding: 10px;
    font-size: 16px;
    color: #fff;
    background: linear-gradient(145deg, #4a90e2, #357ab8);
  }
  
  .modal-button-box button:first-child {
    background: linear-gradient(145deg, #4a90e2, #357ab8);
  }
  
  .modal-button-box button:last-child {
    background: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
  }
  
  .modal-button-box button:first-child:hover {
    background: linear-gradient(145deg, #357ab8, #4a90e2);
  }
  
  .modal-button-box button:first-child:active {
    background: linear-gradient(145deg, #357ab8, #4a90e2);
  }
  
  .modal-button-box button:last-child:hover {
    background: #f5f7fa;
  }
  </style>
  